﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace CineProwl.Domain.Workers
{
    public class ImdbRatingService : WebRequestService, IMovieRatingService  
    {
        private const string URL_TEMPLATE = "http://www.imdb.com/title/{0}/";
        
        public double GetRating(string id)
        {            
            try
            {
                string url = String.Format(URL_TEMPLATE, id);
                string html = this.MakeWebRequest(url);

                double rating = ScrapeRatingHtml(html);
                return rating;
            }
            catch(Exception ex)
            {
                throw new HttpUnhandledException("Unable to retrieve IMDB rating: " + ex.Message, ex);
            }
        }

        private static double ScrapeRatingHtml(string html)
        {
            if (html.Contains("<span itemprop=\"ratingValue\">"))
            {
                html = html.Substring(html.IndexOf("<span itemprop=\"ratingValue\">") + 2);
                html = html.Substring(html.IndexOf(">") + 1);
                html = html[0].ToString() + html[1].ToString() + html[2].ToString();

                double rating;
                if (double.TryParse(html, out rating))
                {
                    return rating;
                }
                throw new HttpParseException("Unable to cast rating to a number - " + html);
            }
            throw new HttpUnhandledException("Http response did not contain the expected rating html");
        }
    }
}
